<?php

class DBUtils {

    private static $instance;
    private $con;

    // A private constructor; prevents direct creation of object
    private function __construct() {

        $dbserver = DBSERVER;
        $dbusername = DBUSER;
        $dbpassword = DBPASSWORD;
        $dbName = DBNAME;
        
        $this->con = mysql_connect($dbserver, $dbusername, $dbpassword);
        mysql_select_db($dbName, $this->con);
        if (!$this->con) {
            print ("Access to DB denied\nYour DB configuration is set to " . SERVER . ". Please make sure you are running on the right environment. You can change the configuration in config.php");
            die;
        }

        /* check connection */

        //if (mysql_connect_error())
        //    throw new Exception("Connect failed: %s\n" . mysql_connect_error());
    }

    // The Create method for singleton class
    public static function Create() {
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

    public function run_query($query) {

        $result = mysql_query($query, $this->con);
        
        //$result = mysqli_query($this->con, $query);
        if (!$result) {
			DEBUG("Invalid show query: $query" . mysql_error(), false);
            die("Invalid query: $query" . mysql_error());
        }
        $rows = array();
        while ($row = mysql_fetch_array($result)) {
            $rows[] = $row;
        }
        return $rows;
    }

    public function run_query_no_reply($query) {

        $result = mysql_query($query, $this->con);
        if (!$result) {
			DEBUG("Invalid query: $query" . mysql_error(), false);
            debug_print_backtrace();
            die("Invalid query: $query" . mysql_error());
        }
    }

    //function that tests the strings and inserts escape characters
    public function f($str) {
        if (is_string($str)) {
            return mysql_escape_string($str);
            //return mysqli_real_escape_string($this->con, $str);
        }
        return $str;
    }

    private function prepParams($argv) {
        for ($i = 0; $i < count($argv); $i+=1) {
            $argv[$i] = $this->f($argv[$i]);
        }

        return $argv;
    }

    //-------------------------------------------LOAD GAME-------------------------------------------------------//

    public function loadGame($gid) {

        $piles = $this->loadPiles($gid);
        $resources = $this->loadResources($gid);
        $players = $this->loadPlayers($gid, $piles, $resources);
        $board = $this->loadBoard($gid, $piles);

        //and we done, we have a game!
        $game = new Game($gid, $players, $board);
        return $game;
    }

    private function loadPiles($gid) {
        //getting all the piles of the game
        $query = "Select * from piles where gid =$gid";
        $r = $this->run_query($query);

        //storing piles for player, the 'board' and 'trash' piles are stored under '0' player
        $player_piles_arr = array();
        foreach ($r as $pile) {
            //name of the user
            $name = $pile['name'];
            //pile type
            $type = $pile['type'];
            //array of cards
            $cards = array();

            //check that it is not an empty pile, otherwise we skip to the end
            if ($pile['cards'] != "") {
                //splitting by |
                $cards_arr = explode("|", $pile['cards']);
                //going over all the cards and create objects from thems
                foreach ($cards_arr as $c) {
                    //the 'board' pile is treated little differently, it also has a sub array contating the quantity of the specific card
                    if (($type == 'board') || ($type == 'durationaffects') || ($type == 'cardsstack')) {
                        $c = explode("~", $c);
                        $subPile = array();
                        for ($i = 2; $i < sizeof($c); $i++) {
                            if ($c[$i] != "")
                                $subPile[] = new $c[$i];
                        }
                        $cards[] = array('card' => new $c[0], 'quantity' => (int) ($c[1]), 'subPile' => $subPile);
                    } else {
                        $cards[] = new $c;
                    }
                }
            }
            //creating new array for the user if not exists
            if (!key_exists($name, $player_piles_arr)) {
                $player_piles_arr[$name] = array();
            }
            //storing the pile under the player
            $player_piles_arr[$name][$type] = $cards;
        }

        //creating the user piles, skipping the '0' plyaer
        $player_piles = array();
        foreach ($player_piles_arr as $name => $pp) {
            if ($name === 0) {
                continue;
            }

            $player_piles[$name] = new Piles(
                            $pp['drawdeck'],
                            $pp['playarea'],
                            $pp['playhand'],
                            $pp['discarddeck'],
                            $pp['cardsstack'],
                            $pp['nativevillage'],
                            $pp['island'],
                            $pp['haven'],
                            $pp['durationaffects'],
                            $pp['influence'],
                            $pp['playedcards'],
                            $pp['gainedcards'],
                            $pp['boughtcards'],
                            $pp['contrabandcards'],
                            $pp['horsetraders'],
                            $pp['reactions']
            );
        }
        //now we add the 0 player (the trash and the board)
        $player_piles[0] = $player_piles_arr[0];
        return $player_piles;
    }

    private function loadResources($gid) {
        $query = "Select * from resources where gid = $gid";
        $r = $this->run_query($query);

        $player_resources = array();
        foreach ($r as $resource_arr) {
            $name = $resource_arr['name'];
            $actions = (int) ($resource_arr['actions']);
            $buys = (int) ($resource_arr['buys']);

            $coins = (int) ($resource_arr['coins']);
            $potions = (int) ($resource_arr['potions']);
            $money = new Price($coins, $potions);

            $victoryTokens = (int) ($resource_arr['victorytokens']);
            $pirateshipTokens = (int) ($resource_arr['pirateshiptokens']);
            $coinTokens = (int) ($resource_arr['cointokens']);
            
            $player_resources[$name] = new Resources($actions, $buys, $money, $victoryTokens, $pirateshipTokens, $coinTokens);
        }
        return $player_resources;
    }

    private function loadPlayers($gid, $piles, $resources) {

        //getting the players, they are stored by order, this way we know whos turn it is now
        $query = "Select * from players where gid =$gid order by myorder";
        $r = $this->run_query($query);

        $players = array();
        foreach ($r as $player_arr) {
            $name = $player_arr['name'];
            $gender = $this->getGender($name);
            $phase = $this->getPhase($name);
            $room = $this->getRoom($name);
            $numberofactionsplayed = $player_arr['numberofactionsplayed'];
            $numberoftreasuresplayed = $player_arr['numberoftreasuresplayed'];
            $numberofturns = (int) ($player_arr['numberofturns']);
            $numberofcardsbought = (int) ($player_arr['numberofcardsbought']);
            $possessedTurns = (int)($player_arr['possessedturns']);
            $undostack = $this->loadUndoStack($gid, $name);
            //and creating the user
            $players[] = new Player(
                            $name,
                            $gender,
                            $piles[$name],
                            $resources[$name],
                            $phase,
                            $room,
                            $numberofactionsplayed,
                            $numberoftreasuresplayed,
                            $numberofturns,
                            $numberofcardsbought,
                            $undostack,
                            $possessedTurns
            );
        }
        return $players;
    }

    private function loadUndoStack($gid, $name) {
        $query = "Select * from undostack where gid=$gid and name = '$name' order by num";
        $res = $this->run_query($query);
        $undoStack = array();
        foreach ($res as $r) {
            $num = $r['num'];
            $action = $r['action'];
            $params = unserialize($r['params']);
            $validUndo = $r['validundo'];
            if ($validUndo == 1)
                $validUndo = true;
            else
                $validUndo = false;
            $undoStack[$num] = array($action, $params, $validUndo);
        }
        return $undoStack;
    }

    private function loadBoard($gid, $piles) {
        //creating the trash
        $trash = $piles['0']['trash'];
        $prizes = $piles['0']['prizes'];
        $board_cards = $piles['0']['board'];
        $embargo_cards = $piles['0']['embargo'];
        $traderoute_cards = $piles['0']['traderoute'];
        $bane_cards = $piles['0']['bane'];
        $black_market_cards = $piles['0']['blackmarket'];
        $all_prizes = $piles['0']['allprizes'];
        $all_blackmarket = $piles['0']['allblackmarket'];
        $spoils_cards = $piles['0']['spoils'];
        $mercenary_cards = $piles['0']['mercenary'];
        $madman_cards = $piles['0']['madman'];
        $shelter_cards = $piles['0']['shelter'];
        //creating the board
        $board = new Board($board_cards, $trash, $prizes, $embargo_cards, $traderoute_cards, $bane_cards, $black_market_cards, $all_prizes, $all_blackmarket, $spoils_cards, $mercenary_cards, $madman_cards, $shelter_cards);
        return $board;
    }

    public function loadUser($name) {
        $name = $this->f($name);
        $query = "Select * from users where name = '$name'";
        $r = $this->run_query($query);

        if (!$r) {
            throw new Exception("No user '$name' found");
        }
        $r = $r[0];
        $gamesPlayed = $r['gamesplayed'];
        $rating = $r['rating'];
        return new User($name, $gamesPlayed, $rating);
    }

    //-------------------------------------------SAVE GAME-------------------------------------------------------//

    public function savePlayer($gid, $name, $order, $numberOfActionsPlayed, $numberOfTreasuresPlayed, $numberOfTurns, $numberOfCardsBought, $undoStack, $possessedTurns) {
        $name = $this->f($name);
        $query = "SELECT * FROM players WHERE gid = $gid and name = '$name'";
        $res = $this->run_query($query);
        if (count($res) == 0) {
            $query = "INSERT INTO players (gid, name, myorder,  numberofactionsplayed, numberoftreasuresplayed,  numberofturns, numberofcardsbought, possessedturns) Values ($gid, '$name',  $order, $numberOfActionsPlayed, $numberOfTreasuresPlayed,  $numberOfTurns , $numberOfCardsBought, $possessedTurns)";
        } else {
            $query = "REPLACE INTO players SET gid=$gid, name='$name', myorder=$order, numberofactionsplayed=$numberOfActionsPlayed, numberoftreasuresplayed=$numberOfTreasuresPlayed,  numberofturns=$numberOfTurns, numberofcardsbought=$numberOfCardsBought, possessedturns = $possessedTurns";
        }
        $this->run_query_no_reply($query);

        $this->clearUndoStack($gid, $name);
        if (sizeof($undoStack) > 0) {
            $query = "REPLACE  INTO undostack (gid, name, num, action,  params, validundo) Values ";
            foreach ($undoStack as $i => $value) {
                $action = $value[0];
                $param = serialize($value[1]);
                $validUndo = $value[2];

                if ($validUndo)
                    $validUndo = 1;
                else
                    $validUndo = 0;

                $query .= "($gid, '$name',  $i, '$action', '$param',$validUndo)";
                if ($i < sizeof($undoStack) - 1)
                    $query .= ",";
            }
            $this->run_query_no_reply($query);
        }
    }

    public function savePile($gid, $name, $type, $cards) {
        $name = $this->f($name);
        $query = "REPLACE INTO piles SET gid=$gid, name='$name', type= '$type', cards = '$cards'";
        $this->run_query_no_reply($query);
    }

    public function saveResources($gid, $name, $actions, $buys, $coins, $potions, $victorytokens, $pirateshiptokens, $cointokens) {
        $name = $this->f($name);
        $query = "REPLACE INTO resources SET gid=$gid, name='$name', actions= $actions, buys = $buys, coins = $coins, potions = $potions, victorytokens = $victorytokens, pirateshiptokens = $pirateshiptokens, cointokens = $cointokens";
        $this->run_query_no_reply($query);
    }

    public function saveUser($name, $gamesPlayed, $rating) {
        $name = $this->f($name);
        $uniqueid = $this->getUniqueID($name);
        $time = time();
        $query = "UPDATE users SET rating = $rating, gamesplayed = $gamesPlayed, lastupdatetime=$time WHERE name= '$name'";
        $this->run_query_no_reply($query);
    }

    //-------------------------------------------OTHER FUNCTIONS-------------------------------------------------------//

    public function newGame() {
        $date = date('d/m/Y H:i');
        // function assumes that gid is auto incrementing
        $query = "Insert into rooms (date) values('$date')";
        DEBUG($query, false);
        $result = mysql_query($query, $this->con);
        $gid = mysql_insert_id($this->con); // gets the new gid from the db.
        return $gid;
    }
    

    public function getAllLogsIDS() {
        $query = "SELECT DISTINCT g.roomid, g.name FROM games_log g order by roomid";
        $r = $this->run_query($query);
        return $r;
    }
    
    public function getRoomDate($roomid) {
        $query = "SELECT date from rooms where gid = $roomid";
        $r = $this->run_query($query);
        if (!$r)
            return null;
        return $r[0]['date'];
    }

    public function getAllUsers() {
        $query = "Select * from users";
        $r = $this->run_query($query);
        $result = array();
        foreach ($r as $res_arr) {
            $user = array();
            $user['name'] = $res_arr['name'];
            $user['level'] = $res_arr['rating'];
            $user['lastupdatetime'] = $res_arr['lastupdatetime'];
            $result[] = $user;
        }
        return $result;
    }

    public function getLobbyUsers() {
        $query = "Select * from users INNER JOIN rooms_to_players ON rooms_to_players.userID = users.name WHERE rooms_to_players.RoomID = 0";
        $r = $this->run_query($query);
        $result = array();
        foreach ($r as $res_arr) {
            $user = array();
            $user['name'] = $res_arr['name'];
            $user['level'] = $res_arr['rating'];
            $result[] = $user;
        }
        return $result;
    }

    public function getPhase($name) {
        $name = $this->f($name);
        $query = "Select phase from rooms_to_players where userID='$name'";
        $res = $this->run_query($query);
        if (sizeof($res) == 0)
            return null;
        return $res[0][0];
    }

    public function getRoom($name) {
        $name = $this->f($name);
        $query = "Select RoomID from rooms_to_players where userID='$name'";        
        $res = $this->run_query($query);
        return $res[0]["RoomID"];
    }
	
	public function getAllGameIDs() {
        $query = "Select RoomID from rooms_to_players where userID='$name'";        
        $res = $this->run_query($query);
        return $res[0]["RoomID"];
    }

    public function setPhase($gid, $name, $phase) {
        $name = $this->f($name);
        $query = "UPDATE rooms_to_players SET phase= '$phase' where RoomID=$gid and userID ='$name'";
        $this->run_query_no_reply($query);

        $this->setUniqueid($name);
    }

    public function getUniqueID($name) {
        $name = $this->f($name);
        $query = "Select uniqueid from users where name='$name'";
        $r = $this->run_query($query);
        return $r[0][0];
    }
    
    public function getChatLinesIDs($roomid) {
        $query = "Select id from chat where roomid = $roomid";
        $r = $this->run_query($query);
        return $r;
    }

    public function setAlert($name, $alert = 1) {
        $name = $this->f($name);
        $query = "UPDATE users SET alert= $alert WHERE name='$name'";
        $this->run_query_no_reply($query);
    }

    public function getAlert($name) {
        $name = $this->f($name);
        $query = "Select alert from users where name='$name'";
        $r = $this->run_query($query);
        $alert = false;
        if ($r[0][0] != "0") {
            $alert = true;
            $query = "UPDATE users SET alert= 0 WHERE name='$name'";
            $this->run_query_no_reply($query);
        }
        return $alert;
    }

    public function getGender($name) {
        $name = $this->f($name);
        $query = "Select gender from users where name='$name'";
        $r = $this->run_query($query);
        return $r[0][0];
    }

    public function setUniqueid($name) {
        $name = $this->f($name);
        $uniqueid = uniqid();
        $query = "UPDATE users SET uniqueid= '$uniqueid' WHERE name='$name'";
        $this->run_query_no_reply($query);
    }

    public function updateLastUpdateTime($name) {
        $name = $this->f($name);
        $uniqueid = uniqid();
        $time = time();
        $query = "UPDATE users SET lastupdatetime= $time WHERE name='$name'";
        $this->run_query_no_reply($query);
    }

    public function addToRoom($room_id, $name) {
        $name = $this->f($name);
        $query = "REPLACE INTO rooms_to_players (RoomID, userID) VALUES ($room_id, '$name')";
        $this->run_query_no_reply($query);
        $this->setUniqueid($name);
    }

    public function removeFromRoom($room_id, $name) {
        $name = $this->f($name);
        $query = "DELETE FROM rooms_to_players WHERE RoomID = $room_id and userID = '$name'";
        $this->run_query_no_reply($query);
        $query = "SELECT * FROM rooms_to_players WHERE RoomID = $room_id";
        $res = $this->run_query($query);
        if (count($res) == 0) {
            $this->deleteRoom($room_id);
        }
    }

    public function clearUndoStack($gid, $name) {
        $name = $this->f($name);
        $query = "DELETE FROM undostack WHERE gid = $gid and name = '$name'";
        $this->run_query_no_reply($query);
    }

    //-------------------------------------- CARDS DATA FUNCTIONS -------------------------------------------------//

    public function saveCardData($gid, $name, $card, $params) {
        $name = $this->f($name);
        $card = $this->f($card);
        $params = $this->f($params);
        $query = "REPLACE INTO carddata SET gid=$gid, name = '$name', card= '$card', params = '$params'";
        $this->run_query_no_reply($query);
    }

    public function deleteCardData($gid, $name, $card) {
        $name = $this->f($name);
        $card = $this->f($card);
        $query = "Delete from carddata Where gid=$gid and name = '$name' and card= '$card'";
        $this->run_query_no_reply($query);
    }

    public function loadCardData($gid, $name, $card) {
        $name = $this->f($name);
        $card = $this->f($card);
        $query = "Select  params from  carddata where gid=$gid and  name = '$name' and  card= '$card'";
        $res = $this->run_query($query);
        if ($res)
            return $res[0]['params'];
        return null;
    }

    //------------------------------------------------- CHAT FUNCTIONS --------------------------------------------------//

    public function setChatLine($roomid, $name, $line) {
        $name = $this->f($name);
        $line = $this->f($line);
        $query = "INSERT INTO chat (roomid, name, line) VALUES ($roomid, '$name', '$line')";
        $this->run_query_no_reply($query);

        /*
        $r = $this->getAllPlayersInRoom($roomid);
        foreach ($r as $player_arr) {
            $other_name = $player_arr['userID'];
            //$this->setUniqueid($other_name);
        }
         */
    }

    public function getChatLines($roomid) {
        $query = "Select id, name, line from chat where roomid=$roomid";
        $res = $this->run_query($query);
        return $res;
    }

    //----------------------------------------------- SCREEN FUNCTIONS --------------------------------------------------//

    public function setScreenMessage($isNewLine, $roomid, $name, $header, $line, $turnNum) {
        $name = $this->f($name);
        $line = $this->f($line);

        if (!$isNewLine) {
            $query = "Select id, line FROM screenmessage where roomid=$roomid and name ='$name' order by id DESC limit 1";
            $r = $this->run_query($query);
            if (sizeof($r) > 0) {
                $line = $r[0]['line'] . $line;
                $id = $r[0]['id'];
                $query = "UPDATE screenmessage SET line='$line', turnnum = $turnNum WHERE id=$id";
            } else {
                throw new Exception("YOU CANT APPEND LINE TO A NON EXISTENT LINE!");
            }
        } else {
            $line = $header . $line;
            $query = "INSERT INTO screenmessage (roomid, name, line, turnnum) VALUES ($roomid, '$name', '$line', $turnNum)";
        }
        $this->run_query_no_reply($query);

        $r = $this->getAllPlayersInRoom($roomid);
        foreach ($r as $player_arr) {
            $other_name = $player_arr['userID'];
            $this->setUniqueid($other_name);
        }
    }

    public function getScreenMessages($roomid, $name = null) {
        $name = $this->f($name);
        $query = "Select line, name, turnnum from screenmessage where roomid=$roomid";
        if ($name)
            $query .= " and name = '$name'";
        $res = $this->run_query($query);
        return $res;
    }

    //------------------------------------------------ LOG FUNCTIONS ---------------------------------------------------//
    /// This function is used to insert a new line to the log table.
    public function logMessage($isNewLine, $roomid, $header, $line, $name) {
        $line = $this->f($line);

        if (!$isNewLine) {
            $query = "Select id, line FROM games_log where roomid=$roomid order by id DESC limit 1";
            $r = $this->run_query($query);
            if (sizeof($r) > 0) {
                $line = $r[0]['line'] . $line;
                $id = $r[0]['id'];
                $query = "UPDATE games_log SET line='$line', name='$name' WHERE id=$id";
            } else {
                throw new Exception("YOU CANT APPEND LINE TO A NON EXISTENT LINE!");
            }
        } else {
            $line = $header . $line;
            $query = "INSERT INTO games_log (roomid, line, name) VALUES ($roomid, '$line', '$name')";
        }
        $this->run_query_no_reply($query);

//        Seems unnecessary as log is not intended for immediate use (Cooper)
//        $r = $this->getAllPlayersInRoom($roomid);
//        foreach ($r as $player_arr) {
//            $other_name = $player_arr['userID'];
//            $this->setUniqueid($other_name);
//        }
    }

    // This function is used to get the entire logged history of a specific game with a given room id
    public function getLogMessages($roomid) {

        $query = "Select line from games_log where roomid=$roomid";
        $res = $this->run_query($query);
        return $res;
    }

    //----------------------------------------------- INPUT FUNCTIONS --------------------------------------------------//

    public function setInput($gid, $name, $inputtype, $params, $min, $max, $extraparams, $screen) {
        $name = $this->f($name);
        $params = $this->f($params);
        $extraparams = $this->f($extraparams);
        $screen = $this->f($screen);

        $query = "REPLACE INTO inputs SET gid=$gid, name='$name', inputtype = '$inputtype',  params = '$params', min = $min, max =$max,  extraparams = '$extraparams', screen='$screen'";
        $this->run_query_no_reply($query);

        $this->setUniqueid($name);
    }

    public function getInput($gid, $name) {
        $name = $this->f($name);
        $query = "SELECT * FROM inputs where  gid=$gid and name = '$name'";
        $res = $this->run_query($query);
        if ($res)
            return $res[0];
        return null;
    }

    public function setOutput($gid, $name, $params) {
        $name = $this->f($name);
        $params = $this->f($params);

        $query = "REPLACE INTO outputs SET gid=$gid, name='$name',  params = '$params'";
        $this->run_query_no_reply($query);
    }

    public function getOutput($gid, $name) {
        $name = $this->f($name);

        $query = "SELECT params FROM outputs where  gid=$gid and name = '$name'";
        $res = $this->run_query($query);
        if ($res)
            return $res[0]['params'];
        return null;
    }

    public function deleteInputOutput($gid, $name) {
        $name = $this->f($name);

        $query = "DELETE FROM inputs where gid=$gid and name = '$name'";
        $this->run_query_no_reply($query);

        $query = "DELETE FROM outputs where gid=$gid and name = '$name'";
        $this->run_query_no_reply($query);
    }

    public function findUser($userid, $hash) {
        $userid = $this->f($userid);
        $hash = $this->f($hash);
        $query = "SELECT * FROM users where  name='$userid' and hash = '$hash'";
        $res = $this->run_query($query);
        if (!$res)
            return false;
        return $res[0];
    }

    public function createUser($userid, $usergender, $userhash) {
        $userid = $this->f($userid);
        $userhash = $this->f($userhash);
        $usergender = $this->f($usergender);

        $uniqueid = $this->getUniqueID($userid);
        $time = time();
        $query = "INSERT INTO users (name, uniqueid, lastupdatetime, gender, hash) VALUES ('$userid', '$uniqueid', $time, '$usergender', '$userhash')";
        $this->run_query_no_reply($query);
    }

    public function getUser($userid, $hash) {
        $userid = $this->f($userid);
        $hash = $this->f($hash);

        $query = "";
        if (SERVER == 'localhost') {
            $query = "SELECT * FROM users where  name='$userid'";
        } else {
            $query = "SELECT * FROM users where  name='$userid' and hash = '$hash'";
        }
        $res = $this->run_query($query);
        if (!$res) {
            return false;
        }
        return true;
    }

    public function setPass($userid, $hash) {
        $userid = $this->f($userid);
        $hash = $this->f($hash);
        $query = "UPDATE users SET users.hash='$hash' WHERE name='$userid'";
        $this->run_query_no_reply($query);
        return true;
    }

    //----------------------------------------------- ROOM FUNCTIONS --------------------------------------------------//

    public function getAllPlayersInRoom($id) {
        $query = "SELECT userID FROM rooms_to_players where RoomID=$id";
        $res = $this->run_query($query);

        return $res;
    }

    public function getAllRoomsForPlayer($name) {
        $name = $this->f($name);

        $query = "SELECT RoomID FROM rooms_to_players WHERE userID = '$name'";
        $res = $this->run_query($query);

        return $res;
    }

    public function deleteRoom($roomid) {
        if ($roomid > 0) { // We do not want to delete lobby even when empty, because gid in rooms is auto incrementing, and thus we can't insert gid 0.
            $query = "DELETE FROM rooms WHERE gid = $roomid";
            $this->run_query_no_reply($query);
        }
    }

    public function clearLobby($lid) {

        $all_users = $this->getAllUsers();
        $dead_users = array();
        $time = time();
        foreach ($all_users as $user_arr) {
            $lut = (int) $user_arr['lastupdatetime'];
            if ($lut < $time - 60) {
                $dead_users[] = $user_arr['name'];
            }
        }
        $someone_deleted = false;
        foreach ($dead_users as $dead_user) {
            $rooms = $this->getAllRoomsForPlayer($dead_user);
            foreach ($rooms as $rid) {
                $someone_deleted = true;
                $this->removeFromRoom($rid[0], $dead_user);
                $this->deleteInputOutput($rid[0], $dead_user);
            }
        }

        return $someone_deleted;
    }

    public function loadLobby($lid) {
        $query = "SELECT userID, phase FROM rooms_to_players WHERE RoomID = $lid";
        $res = $this->run_query($query);
        return $res;
    }

    public function isGameInSession($rid) {
        $query = "select * from rooms_to_players where roomid = $rid and (phase != 'GameOver' and phase != 'GameResign') ";
        $res = $this->run_query($query);
        if ((sizeof($res)) > 0) {
            return true;
        }
        return false;
    }

    public function cleanup() {
        $query = "delete FROM screenmessage where roomid not in (select roomid from rooms_to_players)";
        $this->run_query_no_reply($query);
        $query = "delete FROM undostack where gid not in (select roomid from rooms_to_players)";
        $this->run_query_no_reply($query);
        //$query = "delete FROM rooms where gid not in (select roomid from rooms_to_players) and gid > 0";
        //$this->run_query_no_reply($query);
        $query = "delete FROM resources where gid not in (select roomid from rooms_to_players)";
        $this->run_query_no_reply($query);
        $query = "delete FROM piles where gid not in (select roomid from rooms_to_players)";
        $this->run_query_no_reply($query);
        $query = "delete FROM chat where roomid not in (select roomid from rooms_to_players)";
        $this->run_query_no_reply($query);
        $query = "delete FROM players where gid not in (select roomid from rooms_to_players)";
        $this->run_query_no_reply($query);
    }

}

?>